package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.constant.ArticleStatusEnum;
import org.chen.common.exception.ServiceException;
import org.chen.client.CategoryFeignClient;
import org.chen.mapper.ArticleRepository;
import org.chen.domain.Article;
import org.chen.domain.dto.BatchDeleteDTO;
import org.chen.domain.vo.ArticleVO;
import org.chen.domain.vo.CategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ArticleService {
    
    private final ArticleRepository articleRepository;

    private final CategoryFeignClient categoryFeignClient;

    public Page<ArticleVO> getArticlePage(int current, int size, String source, String categoryId, String keyword) {
        // 创建查询条件
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();

        wrapper.ne(Article::getSource,"admin");

        if (StringUtils.hasText(source)) {
            wrapper.eq(Article::getSource, source);
        }
        if (StringUtils.hasText(categoryId)) {
            wrapper.eq(Article::getCategoryId, categoryId);
        }
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w
                .like(Article::getTitle, keyword)
                .or()
                .like(Article::getDescription, keyword)
            );
        }
        
        wrapper.orderByDesc(Article::getCreateTime);

        // 执行分页查询
        Page<Article> page = articleRepository.selectPage(new Page<>(current, size), wrapper);

        // 获取所有分类ID
        Set<String> categoryIds = page.getRecords().stream()
                .map(Article::getCategoryId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 批量获取分类信息
        Map<String, CategoryVO> categoryMap = new HashMap<>();
        if (!categoryIds.isEmpty()) {
            try {
                List<CategoryVO> categories = categoryFeignClient.getCategoriesByIds(new ArrayList<>(categoryIds)).getData();
                categoryMap = categories.stream()
                        .collect(Collectors.toMap(CategoryVO::getId, category -> category));
            } catch (Exception e) {
                log.error("Failed to get categories", e);
            }
        }

        Map<String, CategoryVO> finalCategoryMap = categoryMap;
        List<ArticleVO> voList = page.getRecords().stream()
                .map(article -> convertToVO(article, finalCategoryMap.get(article.getCategoryId())))
                .collect(Collectors.toList());

        // 构建返回结果
        Page<ArticleVO> result = new Page<>();
        result.setRecords(voList);
        result.setTotal(page.getTotal());
        result.setCurrent(page.getCurrent());
        result.setSize(page.getSize());
        
        return result;
    }

    public ArticleVO getArticleDetail(String id) {
        Article article = articleRepository.selectById(id);
        if (article == null) {
            throw new IllegalArgumentException("Article not found: " + id);
        }
        return convertToVO(article, null);
    }

    private ArticleVO convertToVO(Article article, CategoryVO category) {
        ArticleVO vo = new ArticleVO();
        BeanUtils.copyProperties(article, vo);
        vo.setStatus(ArticleStatusEnum.getDesc(article.getStatus()));
        vo.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .format(article.getCreateTime()));
        vo.setUpdateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .format(article.getUpdateTime()));

        // 设置分类信息
        if (category != null) {
            vo.setCategoryName(category.getName());
        }

        return vo;
    }

    public void deleteArticle(String id) {
        // 检查文章状态，只有未处理的文章才能删除
        Article article = articleRepository.selectById(id);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }

        articleRepository.deleteById(id);
    }

    public void batchDelete(BatchDeleteDTO request) {
        articleRepository.deleteByIds(request.getIds());
    }
}